<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>AndOrStore Demo</title>

<link rel="stylesheet" type="text/css" href="../theme-remote.css" />
<style type="text/css">
body {
    font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
    font-size: 11px;
}

#debugPanel pre {
    font-family: "Lucida Console", "Courier New", Courier, monospace;
}

div.container {
    border: 0px solid green;
    margin: 10px;
}
</style>

<script type="text/javascript">
var djConfig = {
    isDebug: true,
    parseOnLoad: true,
    locale: "zh",
    extraLocale: ["en"],
    baseUrl: "../script/dojo-src/dojo/",
    modulePaths: {
        "demo": "../../demo",
        "com": "../../com"
    }
};
</script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/dojo/1.4.3/dojo/dojo.xd.js.uncompressed.js"></script>
<script type="text/javascript">
    dojo.require("dojo.data.ItemFileWriteStore");
    dojo.require("dojo.date.locale");
    dojo.require("dojo.parser");

    dojo.require("dijit.dijit"); // optimize: load dijit layer
    dojo.require("dijit.ColorPalette");
    dojo.require("dijit.Dialog");
    dojo.require("dijit.form.CheckBox");
    dojo.require("dijit.form.ComboBox");
    dojo.require("dijit.form.Button");
    dojo.require("dijit.form.DateTextBox");
    dojo.require("dijit.form.DropDownButton");
    dojo.require("dijit.form.FilteringSelect");
    dojo.require("dijit.form.NumberSpinner");
    dojo.require("dijit.form.NumberTextBox");
    dojo.require("dijit.form.RadioButton");
    dojo.require("dijit.form.SimpleTextarea");
    dojo.require("dijit.form.Textarea");
    dojo.require("dijit.form.TextBox");
    dojo.require("dijit.form.ValidationTextBox");
    dojo.require("dijit.InlineEditBox");
    dojo.require("dijit.Menu");
    dojo.require("dijit.TitlePane");
    dojo.require("dijit.TooltipDialog");

    dojo.require("dojox.data.AndOrWriteStore");
    dojo.require("dojox.html.entities");
    dojo.require("dojox.layout.FloatingPane");
    dojo.require("dojox.layout.ResizeHandle");
    dojo.require("dojox.widget.Standby");
</script>
<script type="text/javascript" src="../script/utils.js"></script>
<script type="text/javascript" src="../script/grid.js"></script>
<script type="text/javascript">
function debug(messages) {
    var msg = demo.utils._getDebugMsg.apply(null, arguments);
    console.debug(msg);

    var msgDiv = dojo.byId("debugPanelContent");
    msgDiv.innerHTML = msg;
}

function append(messages) {
    var msg = demo.utils._getDebugMsg.apply(null, arguments);

    var msgDiv = dojo.byId("debugPanelContent");
    msgDiv.innerHTML += "\n" + msg;
}

function show(id) {
    demo.utils.show(id);
}

function hide(id) {
    demo.utils.hide(id);
}
</script>
<style type="text/css">
@import "../css/rounded-button.css";
@import "../css/rounded-corners.css";

body {
    padding: 10px;
}

.gridContainer {
    width: 100%;
    height: 300px;
}

/* Column selector pane */
.column-selector-pane {
    vertical-align: top;
}

.column-selector-pane li {
    list-style: none;
}

.highlight {
    background-color: yellow;
}
</style>
<script type="text/javascript">
///////////////////////////////////////////////////////
demo.grid.makeGridStore = function() {
    // Store for grid
    var url = "../data/countries.json";

    var store = new dojox.data.AndOrWriteStore({
        url: url
    });

    return store;
};

demo.grid.makeGridLayout = function(data) {
    var layout = null;

    var columns = [];

    columns.push({
        name: "ID",
        field: "id",
        width: "100px"
    });

    columns.push({
        name: "Name",
        field: "name",
        width: "30%"
    });

    columns.push({
        name: "Type",
        field: "type",
        relWidth: 1
    });

    columns.push({
        name: "Population",
        field: "population",
        relWidth: 1
    });

    dojo.forEach(columns, function(column) {
        column.formatter = highlightFormatter;
    });

    layout = columns;
    return layout;
};

demo.grid.makeGrid = function(nodeId) {
    console.time("grid");
    // initialize tree grid
    var grid = dijit.byId(nodeId);

    if (!grid) {
        //dojo.byId("title").innerHTML = data.metadata.title;
        //demo.grid.formatMetadata(dojo.byId("metadata"), data.metadata.description);
        //dojo.byId("footer").innerHTML = data.metadata.footer || "xxx Confidential";

        // Store for grid
        var store = demo.grid.makeGridStore();

        // Structure for grid
        var layout = demo.grid.makeGridLayout();

        var configuration = {
            node: nodeId
        };

        var params = {
            id: nodeId,
            store: store,
            structure: layout,
            width: "100%",
            autoWidth: false,
            autoHeight: 10,
            columnReordering: true
        };
        configuration.params = params;

        var plugins = {
            indirectSelection: false,
            nestedSorting: true,
            dnd: true,
            menus: {
                //headerMenu: "headerMenu"
                //rowMenu: "rowMenu",
                //cellMenu: "cellMenu",
                //selectedRegionMenu: "selectedRegionMenu"
            }
        };
        configuration.plugins = plugins;

        var eventHandlers = {
            // fix onCellClick to avoid to focus cell when click on cell content
            //"onCellClick": demo.grid.onCellClick
        };
        configuration.eventHandlers = eventHandlers;

        grid = demo.grid.buildGrid(configuration);

        // create header menu
        demo.grid.buildColumnSelectorHeaderMenu(grid);
    }
    console.timeEnd("grid");
};

//////////////////////////////
dojo.addOnLoad(function() {
    debug("loading");

    demo.grid.makeGrid("grid");

    initFieldSelector();
    dojo.connect(dijit.byId("searchKeyword"), "onKeyUp", doSearch);

});

//////////////////////////////

function initFieldSelector() {
    var data = {
        identifier: "field",
        label: "name",
        items: [
            {
                field: "all",
                name: "All",
                show: true
            }
        ]
    };

    var store = new dojox.data.AndOrWriteStore({
        data: data
    });
    var selector = dijit.byId("searchField");
    selector.attr("store", store);
    selector.attr("query", {show: true});
    selector.attr("value", "all");

    var grid = dijit.byId("grid");
    dojo.forEach(getGridColumns(grid), function(column) {
        store.newItem(column);
    });

    dojo.connect(selector, "onChange", function() {
        doSearch();
    });
}

function updateFieldSelector(visibleColumns) {
    var selector = dijit.byId("searchField");
    var store = selector.store;
    var searchField = getSearchField();

    store.fetch({
        query: {
            complexQuery: "NOT field:'all'"
        },
        onComplete: function(items) {
            dojo.forEach(items, function(item) {
                var field = store.getValue(item, "field", null);
                var isVisible = dojo.some(visibleColumns, function(column) {
                    return field === column.field;
                });

                if (!isVisible) {
                    if (field === searchField) {
                        // Current selected option will be deleted, so select "all" instead.
                        selector.attr("value", "all");
                    }
                }

                store.setValue(item, "show", isVisible);
            });
        }
    });
}

function getGridColumns(grid, visibleOption) {
    var columns = [];
    
    var condition = function(cell) {
        if (visibleOption === true) {
            return !cell.hidden;
        }

        if (visibleOption === false) {
            return cell.hidden === true;
        }

        return true;
    };

    dojo.forEach(grid.layout.cells, function(cell) {
        if (condition(cell)) {
            columns.push({
                field: cell.field,
                name: cell.name,
                show: !cell.hidden
            });
        }
    });

    return columns;
}

function getSearchKeyword() {
    var textbox = dijit.byId("searchKeyword");
    var keyword = textbox.attr("value") || null;

    return keyword;
}

function getSearchField() {
    var fieldSelector = dijit.byId("searchField");
    var field = fieldSelector.attr("value");

    return field;
}

function getQueryPattern(field, grid) {
    var fields = [];
    if (field === "all") {
        fields = dojo.map(getGridColumns(grid, true), function(column) {
            return column.field;
        });
    } else {
        fields = [field];
    }

    var patterns = dojo.map(fields, function(field) {
        return field + ": '*{0}*'";
    });

    var queryPattern = patterns.join(" OR ");

    return queryPattern;
}

function highlightFormatter(value, rowIndex) {
    var displayValue = value;

    // highlight
    var searchField = getSearchField();
    if (searchField === "all" || searchField === this.field) {
        var keyword = getSearchKeyword();
        displayValue = demo.utils.highlight(value, keyword);
    }

    return displayValue;
}

////////////////////////////////////////

function doSearch(e) {
    var keyword = getSearchKeyword();
    var field = getSearchField();

    var grid = dijit.byId("grid");

    var query = { id: "*" };
    if (keyword) {
        var queryPattern = getQueryPattern(field, grid);
        var complexQuery = demo.utils.format(queryPattern, keyword);
        query = { complexQuery: complexQuery };
        console.debug(complexQuery);
    }

    // do filter
    grid.filter(query);
}


// showColumnSelectorDialogButton
function showColumnSelectorDialog() {
    var grid = dijit.byId("grid");
    demo.grid.buildColumnSelectorContainer(grid, "columnSelectorContainer", 10);
    dijit.byId("gridColumnsDialog").show();
}

// showColumnsButton
function showColumns() {
    var grid = dijit.byId("grid");

    demo.grid.showSelectedColumns(grid, updateFieldSelector);
    dijit.byId("gridColumnsDialog").hide();
}
</script>
</head>
<body class="tundra">

  <div id="main" class="container">

    <div id="titlePanel" dojoType="dijit.TitlePane" title="Panel" style="">
      <div id="resizablePanel" style="position:relative; padding: 10px; border:1px solid black;">

        <!-- Content -->
        <div class="content">
            <div id="title" style="font-weight: bold;"></div>
            <!-- grid toolbar -->
            <div id="gridToolbarContainer">
              <!-- Search Box -->
              <label for="searchKeyword">Search:</label><input id="searchKeyword" type="text" dojoType="dijit.form.TextBox" />
              <!-- Field Selector -->
              <label for="searchField">within:</label>
              <select id="searchField" dojoType="dijit.form.FilteringSelect"></select>
            </div>
            <!-- grid -->
            <div id="grid"></div>
            <div id="metadata"></div>
            <div id="footer" style="text-align: center; font-weight: bold; font-size: smaller; color: #880000;"></div>
        </div>

        <!-- Resize Handle -->
        <div id="resizeHandle" dojoType="dojox.layout.ResizeHandle" targetId="resizablePanel"></div>
      </div>
    </div>

    <!-- Button Panel -->
    <div dojoType="dojo.dnd.Moveable">
      <div id="buttonPanel" dojoType="dijit.TitlePane" title="Button Panel" style="">
        <!-- Show "Select columns to display" dialog -->
        <button dojoType="dijit.form.Button" onClick="showColumnSelectorDialog();">Show columns dialog</button>

        <!-- Drop Down Button -->
        <button dojoType="dijit.form.DropDownButton" iconClass="noteIcon" title="Select columns" value="Select columns" menu="">
          <span>Select columns</span>
          <!-- Header Menu -->
          <div dojoType="dijit.Menu" id="headerMenu" style="display: none;">
            <div dojoType="dojox.widget.PlaceholderMenuItem" label="GridColumns"></div>
          </div>
        </button>

        <!-- Restore columns -->
        <button dojoType="dijit.form.Button" onClick="restoreColumns();">Restore columns</button>
      </div>
    </div>
  </div>

  <!-- Debug Panel -->
  <div id="debugPanel" dojoType="dojox.layout.FloatingPane" title="Console" resizable="true" dockable="true" style="position: absolute; bottom: 20px; right: 20px; width: 500px; height: 150px;">
    <pre id="debugPanelContent"></pre>
  </div>

  <!-- Show Columns Dialog -->
  <div dojoType="dijit.Dialog" id="gridColumnsDialog" title="Select Columns" style="display: none;">
    <div id="columnSelectorContainer"></div>
    <div style="clear: both;" class="hrule-dots">&nbsp;</div>
    <div id="showColumnsButton" dojoType="dijit.form.Button" onClick="showColumns();">Show columns</div>
    <div id="cancelSelectColumnsButton" dojoType="dijit.form.Button" onClick="cancelSelectColumns();">Cancel</div>
  </div>
</body>
</html>
